/**
 * 阀门历史记录
 */
'use strict';


const conn = require('../../libs/DB/Conn');
const _ = require("underscore");
const decimal = require("decimal");
const {timeComponent,chartDataProcessing} = require("../../libs/Utils")
const moment = require("moment/moment");
const columnNameObj = require("./deviceChartConfig").chart.valve;
const deviceType = require("./deviceChartConfig").type.valve;

module.exports = async function (params) {
    try{
    let timeInterval = timeComponent(params.startTime,params.endTime,params.type);
    let sql = `SELECT
        dd.device_no AS deviceNo,
        DATE_FORMAT(dd.data_time,"%Y-%m-%d %H:%i:%s") AS dataTime,
        DATE_FORMAT(dd.valve_closing_time,"%Y-%m-%d %H:%i:%s") AS valveClosingTime,
        ${timeInterval.queryGroupTime} 
        df.device_name AS deviceName,
        dd.accumulated_time AS accumulatedTime,
        dd.accumulated_time_consumption AS accumulatedTimeConsumption,
        dd.allocated_accumulated_time AS allocatedAccumulatedTime,
        dd.allocated_accumulated_time_consumption AS allocatedAccumulatedTimeConsumption,
        dd.valve_closing_time AS valveClosingTime,
        dd.valve_closing_time_consumption AS valveClosingTimeConsumption,
        dd.accumulated_heat AS accumulatedHeat,
        dd.consumption_heat AS consumptionHeat,
        dd.preset_temperature AS presetTemperature,
        dd.indoor_temperature AS indoorTemperature,
        dd.supply_water_temperature AS supplyWaterTemperature,
        dd.return_water_temperature AS returnWaterTemperature,
        dd.apportionment_factor AS apportionmentFactor,
        dd.area,
        dd.serial_number AS serialNumber,
        dd.type,
        rf.range_name AS rangeName
    FROM
    data_valve_${params.userDomainId} dd
    INNER JOIN device_file df ON df.device_no = dd.device_no
    AND df.delete_sign = 1 AND df.device_type = ${deviceType} 
    AND df.range_id IN (?)
    INNER JOIN range_file rf ON df.range_id = rf.range_id AND rf.delete_sign = 1 
    WHERE 1 = 1 ${timeInterval.startTime && timeInterval.endTime ? ` AND (dd.data_time > "${timeInterval.startTime}" AND dd.data_time <= "${timeInterval.endTime}")` : `` } 
    ORDER BY dd.data_time DESC`;
    let valveDataList = await conn(sql,[params.rangeIds]);
    let valveDataGroup = _.groupBy(valveDataList,"deviceNo");
    let dataList = [];
    for(const deviceNo in valveDataGroup){
        let deviceDataList = valveDataGroup[deviceNo];
        let deviceObj = {
            deviceName:deviceDataList[0].deviceName,
            rangeName:deviceDataList[0].rangeName,
            deviceNo:deviceNo,
            accumulatedTime:deviceDataList[0].accumulatedTime,
            accumulatedTimeConsumption:"00:00:00",
            allocatedAccumulatedTime:deviceDataList[0].allocatedAccumulatedTime,
            allocatedAccumulatedTimeConsumption:"00:00:00",
            valveClosingTime:deviceDataList[0].valveClosingTime,
            valveClosingTimeConsumption:"00:00:00",
            accumulatedHeat:deviceDataList[0].accumulatedHeat,
            consumptionHeat:0,
            presetTemperature:deviceDataList[0].presetTemperature,
            indoorTemperature:deviceDataList[0].indoorTemperature,
            supplyWaterTemperature:deviceDataList[0].supplyWaterTemperature,
            returnWaterTemperature:deviceDataList[0].returnWaterTemperature,
            apportionmentFactor:deviceDataList[0].apportionmentFactor,
            area:deviceDataList[0].area,
            serialNumber:deviceDataList[0].serialNumber,
            type:deviceDataList[0].type,
            dataList:[],
        }
        deviceDataList.forEach(function (data){
            let accumulatedTimeConsumption = moment.duration(deviceDataList[0].accumulatedTimeConsumption).add(moment.duration(data.accumulatedTimeConsumption));
            deviceObj.accumulatedTimeConsumption =  moment.utc(accumulatedTimeConsumption.asMilliseconds()).format('HH:mm:ss')
            let allocatedAccumulatedTimeConsumption = moment.duration(deviceDataList[0].allocatedAccumulatedTimeConsumption).add(moment.duration(data.allocatedAccumulatedTimeConsumption));
            deviceObj.allocatedAccumulatedTimeConsumption =  moment.utc(allocatedAccumulatedTimeConsumption.asMilliseconds()).format('HH:mm:ss')
            let valveClosingTimeConsumption = moment.duration(deviceDataList[0].valveClosingTimeConsumption).add(moment.duration(data.valveClosingTimeConsumption));
            deviceObj.valveClosingTimeConsumption =  moment.utc(valveClosingTimeConsumption.asMilliseconds()).format('HH:mm:ss')
            deviceObj.consumptionHeat =  decimal.add(deviceObj.consumptionHeat,data.consumptionHeat).internal
        })
        if(params.type === "hour"){
            deviceObj.dataList = deviceDataList
        }else {
            let timeGroup = _.groupBy(deviceDataList,"groupTime");
            for(const time in timeGroup){
                let timeGroupList = timeGroup[time];
                let deviceDataObj = {
                    dataTime:time,
                    dataCreateTime:timeGroupList[timeGroupList.length - 1].dataTime,
                    accumulatedTime:timeGroupList[0].accumulatedTime,
                    accumulatedTimeConsumption:"00:00:00",
                    allocatedAccumulatedTime:timeGroupList[0].allocatedAccumulatedTime,
                    allocatedAccumulatedTimeConsumption:"00:00:00",
                    valveClosingTime:timeGroupList[0].valveClosingTime,
                    valveClosingTimeConsumption:"00:00:00",
                    accumulatedHeat:timeGroupList[0].accumulatedHeat,
                    consumptionHeat:0,
                    presetTemperature:timeGroupList[0].presetTemperature,
                    indoorTemperature:timeGroupList[0].indoorTemperature,
                    supplyWaterTemperature:timeGroupList[0].supplyWaterTemperature,
                    returnWaterTemperature:timeGroupList[0].returnWaterTemperature,
                    apportionmentFactor:timeGroupList[0].apportionmentFactor,
                    area:timeGroupList[0].area,
                    serialNumber:timeGroupList[0].serialNumber,
                    type:timeGroupList[0].type
                }
                deviceDataList.forEach(function (data){
                    let accumulatedTimeConsumption = moment.duration(deviceDataObj.accumulatedTimeConsumption).add(moment.duration(data.accumulatedTimeConsumption));
                    deviceDataObj.accumulatedTimeConsumption =  moment.utc(accumulatedTimeConsumption.asMilliseconds()).format('HH:mm:ss')
                    let allocatedAccumulatedTimeConsumption = moment.duration(deviceDataObj.allocatedAccumulatedTimeConsumption).add(moment.duration(data.allocatedAccumulatedTimeConsumption));
                    deviceDataObj.allocatedAccumulatedTimeConsumption =  moment.utc(allocatedAccumulatedTimeConsumption.asMilliseconds()).format('HH:mm:ss')
                    let valveClosingTimeConsumption = moment.duration(deviceDataObj.valveClosingTimeConsumption).add(moment.duration(data.valveClosingTimeConsumption));
                    deviceDataObj.valveClosingTimeConsumption =  moment.utc(valveClosingTimeConsumption.asMilliseconds()).format('HH:mm:ss')
                    deviceDataObj.consumptionHeat =  decimal.add(deviceDataObj.consumptionHeat,data.consumptionHeat).internal
                })
                deviceObj.dataList.push(deviceDataObj);
            }
        }
        deviceObj.chart = chartDataProcessing(deviceObj.dataList,columnNameObj);
        dataList.push(deviceObj);
    }
    return { success: true,dataList:dataList};
    }catch (e){
        return { success: false,dataList:[],message:e.code === "ER_NO_SUCH_TABLE" ? "当前账号无此类设备" : e.sqlMessage};
    }
};